package com.buka.service.impl;

import cn.hutool.core.util.StrUtil;
import com.buka.common.BizCodeEnum;
import com.buka.interceptor.LoginUserInterceptor;
import com.buka.util.CommonUtil;
import com.buka.util.JsonData;
import com.buka.vo.LoginUserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MailService {

    private static final String EMAIL_TITLE = "BUKA科技注册验证码" ;
    private static final String EMAIL_CONTENT = "布卡科技欢迎您注册，请使用当前验证码发起注册，验证码有效时间5分钟。验证码为：" ;


    @Value("${spring.mail.from}")
    private String from;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    RedisTemplate redisTemplate;


    /**
     * 收件人
     * 主题
     * 发送内容
     *
     * @return
     */
    public boolean sendEmail(String to, String title, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);//发送者
        simpleMailMessage.setTo(to);//收件人
        simpleMailMessage.setSubject(title);//主题
        simpleMailMessage.setText(content);//邮件内容
        log.info("收件人：{},主题：{},内容：{}",to, title, content);
        javaMailSender.send(simpleMailMessage);

        return true;
    }

    public JsonData sendCode(String mail, HttpServletRequest request) {
        //如果邮箱  随便输入的（乱码） 不允许发送验证码  校验邮箱是否正确
        if(!CommonUtil.checkMail(mail)){
            return JsonData.buildResult(BizCodeEnum.MAIL_ERR);
        }

        String mailCodeKey = "user:mail:"+ mail;
        //邮件只能发送一次
        String mailCode = (String) redisTemplate.opsForValue().get(mailCodeKey);
        if(StrUtil.isNotBlank(mailCode)){
            return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
        }

        //发邮件
        String randomCode = CommonUtil.getRandomCode(6);
        sendEmail(mail,EMAIL_TITLE,EMAIL_CONTENT + randomCode);
        //邮件发送成功之后，将验证码存入redis ,因为注册时需要验证邮箱验证码是否正确
        //使用邮箱作为唯一key
        redisTemplate.opsForValue().set(mailCodeKey,randomCode,365, TimeUnit.DAYS);
        return JsonData.buildSuccess();
    }


    public boolean checkMailCode(String mail,String code){

        String old_code = (String) redisTemplate.opsForValue().get("user:mail:" + mail);
        if(StrUtil.equals(code,old_code)){
            return true;
        }
        return false;
    }
}
